/**
 * 给定排序数组和目标值，数组中已有则返回其索引；数组中没有则按顺序插入
 * @param {number[]} nums 
 * @param {number} pos 
 */
var searchInsertPosition = function (nums, val) {
    let set = new Set(nums)
    if (set.has(val)) {
        return nums.indexOf(val)
    } else {
        set.add(val)
        return Array.from(set).sort((a, b) => { return a - b }).indexOf(val)
    }
}

// 二分法
var searchInsertPosition2 = function (nums, target) {
    if (nums.length === 0) {
        return 0
    }
    let left = 0, right = nums.length - 1
    while (left < right) {
        let mid = left + Math.floor((right - left) / 2)
        if (nums[mid] === target) {
            return mid
        } else if (nums[mid] > target) {
            right = mid
        } else {
            left = mid + 1
        }
    }
    
    if (nums[left] >= target) {
        return left
    } else {
        return left + 1
    }
}